/*
 * SearchFrame.java
 *
 * Created on 28 listopad 2007, 17:12
 */

package pl.edu.pw.mini.gui;

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import pl.edu.pw.mini.adapter.GoogleStrategy;
import pl.edu.pw.mini.adapter.IAdapterStrategy;
import pl.edu.pw.mini.adapter.IConnectionState;
import pl.edu.pw.mini.adapter.ZohoStrategy;
import pl.edu.pw.mini.exceptions.AuthenticationException;
import pl.edu.pw.mini.exceptions.ConnectionException;
import pl.edu.pw.mini.user.UserData;

/**
 * Frame that allows user to connect to google and zoho servers and save / test user's data (login and password)
 * @author Diana
 */
public class SetupFrame extends javax.swing.JFrame {
    
    interface AdapterGroup extends IAdapterStrategy{
        javax.swing.JButton getBtnDisconnect();
        javax.swing.JButton getBtnTest();
        javax.swing.JButton getBtnSave();
        javax.swing.JCheckBox getChbSavePassword();
        javax.swing.JLabel getLabel();
        javax.swing.JLabel getStatus();
        javax.swing.JTextField getLogin();
        javax.swing.JPasswordField getPassword();
    }
    
    protected class GoogleAdapterGroup extends GoogleStrategy implements AdapterGroup{
        public JButton getBtnDisconnect() {
            return btnGoogleDisconnect;
        }

        public JButton getBtnTest() {
            return btnGoogleTest;
        }

        public JButton getBtnSave() {
            return btnGoogleSave;
        }

        public JCheckBox getChbSavePassword() {
            return chbGoogleSavePassword;            
        }

        public JLabel getLabel() {
            return googleLabel;            
        }

        public JLabel getStatus() {
            return txtGoogleStatus;
        }

        public JTextField getLogin() {
            return txtGoogleLogin;
        }

        public JPasswordField getPassword() {
            return txtGooglePassword;
        }
    }

    private AdapterGroup googleAdapter=new GoogleAdapterGroup();

    protected  class ZohoAdapterGroup extends ZohoStrategy implements AdapterGroup{
        public JButton getBtnDisconnect() {
            return btnZohoDisconnect;
        }

        public JButton getBtnTest() {
            return btnZohoTest;
        }

        public JButton getBtnSave() {
            return btnZohoSave;
        }

        public JCheckBox getChbSavePassword() {
            return chbZohoSavePassword;            
        }

        public JLabel getLabel() {
            return zohoLabel;            
        }

        public JLabel getStatus() {
            return txtZohoStatus;
        }

        public JTextField getLogin() {
            return txtZohoLogin;
        }

        public JPasswordField getPassword() {
            return txtZohoPassword;
        }        
    }
    
    private AdapterGroup zohoAdapter=new ZohoAdapterGroup();
    
    
    /** Creates new form SearchFrame */
    public SetupFrame() {
        initComponents();
        initialGroupSettings(googleAdapter);
        initialGroupSettings(zohoAdapter);
        renderState();
    }

    private void initialGroupSettings(AdapterGroup group) {
        String login="";
        String password="";
        IConnectionState cs=group.getConnectionState();
        if (cs == null || cs.isPasswordEmpty()){
            UserData user = group.getUserData();
            login = user.login;
            group.getStatus().setText("Not connected");
            group.getStatus().setForeground(Color.RED);
            group.getChbSavePassword().setSelected(user.savePassword);
        } else{
            login=cs.getLogin();
            password="";
            group.getStatus().setText("Connected");
            group.getStatus().setForeground(Color.GREEN);
        }
        group.getLogin().setText(login);
        group.getPassword().setText(password);
    }

    private void renderState(AdapterGroup group){
        if (group.getConnectionState()==null || group.getConnectionState().isPasswordEmpty()){
            group.getLabel().setForeground(Color.RED);
            group.getBtnDisconnect().setEnabled(false);
        }
        else{
            group.getLabel().setForeground(Color.GREEN);
            group.getBtnDisconnect().setEnabled(true);            
        }
    }
    
    private void renderState(){
        renderState(googleAdapter);
        renderState(zohoAdapter);
    }
    
    private boolean nonEmpty(String str){
        return str!=null && !"".equals(str);
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        googleLabel = new javax.swing.JLabel();
        zohoLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        chbGoogleSavePassword = new javax.swing.JCheckBox();
        chbZohoSavePassword = new javax.swing.JCheckBox();
        txtGoogleLogin = new javax.swing.JTextField();
        txtZohoLogin = new javax.swing.JTextField();
        txtGooglePassword = new javax.swing.JPasswordField();
        txtZohoPassword = new javax.swing.JPasswordField();
        btnOK = new javax.swing.JButton();
        btnGoogleTest = new javax.swing.JButton();
        btnZohoTest = new javax.swing.JButton();
        txtGoogleStatus = new javax.swing.JLabel();
        txtZohoStatus = new javax.swing.JLabel();
        btnGoogleSave = new javax.swing.JButton();
        btnGoogleDisconnect = new javax.swing.JButton();
        btnZohoSave = new javax.swing.JButton();
        btnZohoDisconnect = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabelStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Settings");
        getAccessibleContext().setAccessibleName("Settings");
        googleLabel.setText("Google:");

        zohoLabel.setText("Zoho:");

        jLabel3.setText("Login:");

        jLabel4.setText("Password:");

        jLabel5.setText("Login:");

        jLabel6.setText("Password:");

        chbGoogleSavePassword.setText("Save password");
        chbGoogleSavePassword.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        chbGoogleSavePassword.setMargin(new java.awt.Insets(0, 0, 0, 0));

        chbZohoSavePassword.setText("Save password");
        chbZohoSavePassword.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        chbZohoSavePassword.setMargin(new java.awt.Insets(0, 0, 0, 0));

        txtGoogleLogin.setNextFocusableComponent(txtGooglePassword);

        txtZohoLogin.setNextFocusableComponent(txtZohoPassword);

        txtGooglePassword.setNextFocusableComponent(btnGoogleTest);

        txtZohoPassword.setNextFocusableComponent(btnZohoTest);

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnGoogleTest.setText("Test");
        btnGoogleTest.setNextFocusableComponent(btnGoogleSave);
        btnGoogleTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGoogleTestActionPerformed(evt);
            }
        });

        btnZohoTest.setText("Test");
        btnZohoTest.setNextFocusableComponent(btnZohoSave);
        btnZohoTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnZohoTestActionPerformed(evt);
            }
        });

        txtGoogleStatus.setForeground(new java.awt.Color(255, 0, 0));

        btnGoogleSave.setText("Save");
        btnGoogleSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGoogleSaveActionPerformed(evt);
            }
        });

        btnGoogleDisconnect.setText("Disconnect");
        btnGoogleDisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGoogleDisconnectActionPerformed(evt);
            }
        });

        btnZohoSave.setText("Save");
        btnZohoSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnZohoSaveActionPerformed(evt);
            }
        });

        btnZohoDisconnect.setText("Disconnect");
        btnZohoDisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnZohoDisconnectActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabelStatus.setText("Status: Idle");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(233, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(zohoLabel)
                            .addComponent(googleLabel)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6))
                                .addGap(17, 17, 17)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtZohoPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                                    .addComponent(txtGooglePassword, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                                    .addComponent(txtGoogleLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                                    .addComponent(chbGoogleSavePassword)
                                    .addComponent(chbZohoSavePassword)
                                    .addComponent(txtGoogleStatus)
                                    .addComponent(txtZohoStatus)
                                    .addComponent(txtZohoLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(52, 52, 52)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(btnZohoDisconnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btnZohoTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btnZohoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(btnGoogleDisconnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btnGoogleSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btnGoogleTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(141, 141, 141)
                        .addComponent(btnOK)))
                .addContainerGap())
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(googleLabel)
                    .addComponent(txtGoogleStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtGoogleLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnGoogleTest))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtGooglePassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnGoogleSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(chbGoogleSavePassword)
                        .addGap(65, 65, 65)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(zohoLabel)
                            .addComponent(txtZohoStatus)))
                    .addComponent(btnGoogleDisconnect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(btnZohoTest)
                    .addComponent(txtZohoLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtZohoPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnZohoSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chbZohoSavePassword)
                    .addComponent(btnZohoDisconnect))
                .addGap(17, 17, 17)
                .addComponent(btnOK)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void adapterDisconnectAction(AdapterGroup group){
        group.setConnectionState(null);
        group.getStatus().setText("Disconnected");
        group.getStatus().setForeground(Color.RED);
        renderState(group);
    }
    
    private void btnZohoDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZohoDisconnectActionPerformed
        adapterDisconnectAction(zohoAdapter);
    }//GEN-LAST:event_btnZohoDisconnectActionPerformed

    private void adapterSaveAction(AdapterGroup group){
        UserData userData = new UserData(group.getLogin().getText(), group.getPassword().getText(), group.getChbSavePassword().isSelected());
        if(!userData.savePassword)
            userData.password = "";
        group.setUserData(userData);
        jLabelStatus.setText("Status: Logging in...");
        this.update(this.getGraphics());
        group.setConnectionState(getGroupConnectionStateConditionallyWithWarnings(group));
        renderState();
        jLabelStatus.setText("Status: Idle");
        this.update(this.getGraphics());        
    }
    
    private void btnZohoSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZohoSaveActionPerformed
        adapterSaveAction(zohoAdapter);
    }//GEN-LAST:event_btnZohoSaveActionPerformed
    
    private void btnGoogleSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGoogleSaveActionPerformed
        adapterSaveAction(googleAdapter);
    }//GEN-LAST:event_btnGoogleSaveActionPerformed
    
    private void btnGoogleDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGoogleDisconnectActionPerformed
        adapterDisconnectAction(googleAdapter);
    }//GEN-LAST:event_btnGoogleDisconnectActionPerformed

    private IConnectionState getGroupConnectionStateConditionallyWithWarnings(AdapterGroup group){
        String login = group.getLogin().getText();
        String password = new String(group.getPassword().getPassword());
        JLabel txtStatus = group.getStatus();
        txtStatus.setText("");
        txtStatus.setForeground(Color.RED);
        if (!nonEmpty(login)){
            txtStatus.setText("Login missing !");
            return null;
        }
        if (!nonEmpty(password)){
            txtStatus.setText("Password missing !");
            return null;
        }
        IConnectionState cs = group.getAdapter().createConnectionState(login,password);
        try{
            group.getAdapter().logIn(cs);
        } catch(AuthenticationException ex){
            txtStatus.setText("Authentication failure !");
            return null;
        } catch(ConnectionException ex){
            txtStatus.setText("Connection failure !");
            return null;
        }
        txtStatus.setText("Connection established");
        txtStatus.setForeground(Color.GREEN);
        return cs;
    }
    
    private void adapterTestAction(AdapterGroup group){
        jLabelStatus.setText("Status: Logging in...");
        this.update(this.getGraphics());
        getGroupConnectionStateConditionallyWithWarnings(group);
        jLabelStatus.setText("Status: Idle");
        this.update(this.getGraphics());        
    }
    
    private void btnZohoTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZohoTestActionPerformed
        adapterTestAction(zohoAdapter);
    }//GEN-LAST:event_btnZohoTestActionPerformed
    
    private void btnGoogleTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGoogleTestActionPerformed
        adapterTestAction(googleAdapter);
    }//GEN-LAST:event_btnGoogleTestActionPerformed
    
    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        this.setVisible(false);
        refreshUserData(zohoAdapter);
        refreshUserData(googleAdapter);
    }//GEN-LAST:event_btnOKActionPerformed
    
    private void refreshUserData(AdapterGroup group){
        UserData user = group.getUserData();
        group.getLogin().setText(user.login);
        group.getChbSavePassword().setSelected(user.savePassword);
    }
    /**
     * @param args the command line arguments
     */
  /*  public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SetupFrame().setVisible(true);
            }
        });
    } */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGoogleDisconnect;
    private javax.swing.JButton btnGoogleSave;
    private javax.swing.JButton btnGoogleTest;
    private javax.swing.JButton btnOK;
    private javax.swing.JButton btnZohoDisconnect;
    private javax.swing.JButton btnZohoSave;
    private javax.swing.JButton btnZohoTest;
    private javax.swing.JCheckBox chbGoogleSavePassword;
    private javax.swing.JCheckBox chbZohoSavePassword;
    private javax.swing.JLabel googleLabel;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelStatus;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtGoogleLogin;
    private javax.swing.JPasswordField txtGooglePassword;
    private javax.swing.JLabel txtGoogleStatus;
    private javax.swing.JTextField txtZohoLogin;
    private javax.swing.JPasswordField txtZohoPassword;
    private javax.swing.JLabel txtZohoStatus;
    private javax.swing.JLabel zohoLabel;
    // End of variables declaration//GEN-END:variables
}
